<template>
	<view class="apply-container">
		<view class="form-card">
			<view class="form-title">申请设备维保</view>
			
			<view class="form-item">
				<view class="item-label required">设备选择</view>
				<view class="item-content">
					<view class="device-selector" @click="showDeviceSelector">
						<text v-if="selectedDevice" class="selected-text">{{ selectedDevice.device_name }} ({{ selectedDevice.device_number }})</text>
						<text v-else class="placeholder">请选择需要维保的设备</text>
						<uni-icons type="right" size="16" color="#BBBBBB"></uni-icons>
					</view>
				</view>
			</view>
			
			<view class="form-item">
				<view class="item-label required">维保内容</view>
				<view class="item-content">
					<textarea 
						class="form-textarea" 
						v-model="formData.content" 
						placeholder="请详细描述维保内容、故障现象等信息"
						maxlength="500"
					></textarea>
					<view class="textarea-counter">{{ formData.content.length }}/500</view>
				</view>
			</view>
			
			<view class="form-item">
				<view class="item-label required">故障描述</view>
				<view class="item-content">
					<textarea 
						class="form-textarea" 
						v-model="formData.fault_description" 
						placeholder="请描述设备故障情况"
						maxlength="500"
					></textarea>
					<view class="textarea-counter">{{ formData.fault_description.length }}/500</view>
				</view>
			</view>
			
			<view class="form-item">
				<view class="item-label">故障照片</view>
				<view class="item-content">
					<view class="upload-images">
						<view 
							v-for="(item, index) in formData.media_list" 
							:key="index" 
							class="image-item"
						>
							<image 
								:src="item.url" 
								mode="aspectFill" 
								class="preview-image" 
								@click="previewImage(index)"
							></image>
							<view class="delete-icon" @click.stop="deleteImage(index)">
								<uni-icons type="trash" size="18" color="#FFFFFF"></uni-icons>
							</view>
						</view>
						
						<view 
							class="upload-button" 
							@click="chooseImage" 
							v-if="formData.media_list.length < 3"
						>
							<uni-icons type="camera" size="24" color="#BBBBBB"></uni-icons>
							<text class="upload-text">上传照片</text>
						</view>
					</view>
					<text class="upload-tip">最多上传3张图片</text>
				</view>
			</view>
			
			<view class="form-item">
				<view class="item-label required">期望维修时间</view>
				<view class="item-content">
					<picker 
						mode="date" 
						:value="formData.expected_time" 
						:start="getCurrentDate()" 
						@change="onDateChange"
					>
						<view class="picker-view">
							<text v-if="formData.expected_time">{{ formData.expected_time }}</text>
							<text v-else class="placeholder">请选择期望维修日期</text>
							<uni-icons type="calendar" size="16" color="#BBBBBB"></uni-icons>
						</view>
					</picker>
				</view>
			</view>
		</view>
		
		<view class="submit-section">
			<button class="submit-btn" @click="submitForm" :disabled="submitting">
				{{ submitting ? '提交中...' : '提交申请' }}
			</button>
		</view>
		
		<!-- 设备选择弹窗 (自定义模态框) -->
		<view class="custom-modal" v-if="showDeviceModal">
			<view class="modal-mask" @click="closeDevicePopup"></view>
			<view class="modal-content">
				<view class="popup-header">
					<text class="popup-title">选择设备</text>
					<view class="popup-close" @click="closeDevicePopup">
						<uni-icons type="close" size="20" color="#666"></uni-icons>
					</view>
				</view>
				
				<view class="popup-body">
					<view class="search-box">
						<uni-icons type="search" size="16" color="#999"></uni-icons>
						<input 
							class="search-input" 
							v-model="deviceSearchKey" 
							placeholder="搜索设备名称或编号"
							@input="searchDevices"
						/>
					</view>
					
					<scroll-view scroll-y class="device-list">
						<view v-if="loadingDevices" class="loading-devices">
							<uni-load-more status="loading" :contentText="loadingText"></uni-load-more>
						</view>
						
						<view v-else-if="filteredDevices.length === 0" class="empty-devices">
							暂无设备数据
						</view>
						
						<view 
							v-else
							v-for="(device, index) in filteredDevices" 
							:key="index" 
							class="device-item"
							@click="selectDevice(device)"
						>
							<view class="device-info">
								<view class="device-name">{{ device.device_name }}</view>
								<view class="device-number">{{ device.device_number }}</view>
							</view>
							<view class="device-type">{{ device.device_type }}</view>
						</view>
					</scroll-view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { createDeviceMaintenance, getAvailableDevices } from '@/api/services.js'
	import eventBus from '@/utils/eventBus.js'
	
	export default {
		data() {
			return {
				formData: {
					device_id: '',
					maintenance_type: '维修', // 默认为维修，不再由用户选择
					content: '',
					expected_time: '', // 期望维修时间
					fault_description: '', // 故障描述，对应repair_service表
					repair_status: '待处理', // 默认状态为待处理
					media_list: [] // 故障照片列表
				},
				selectedDevice: null,
				deviceList: [], // 从后端获取设备列表，不再使用模拟数据
				filteredDevices: [],
				deviceSearchKey: '',
				loadingDevices: false,
				submitting: false,
				showDeviceModal: false,
				loadingText: {
					contentdown: '正在加载...',
					contentrefresh: '正在加载...',
					contentnomore: '没有更多数据了'
				}
			}
		},
		computed: {
			// 将图片列表转换为URL数组，用于提交到后端
			mediaUrls() {
				return this.formData.media_list.map(item => item.url)
			}
		},
		onLoad() {
			// 从后端加载设备列表
			this.getDeviceList()
		},
		methods: {
			// 获取当前日期
			getCurrentDate() {
				const date = new Date()
				const year = date.getFullYear()
				const month = (date.getMonth() + 1).toString().padStart(2, '0')
				const day = date.getDate().toString().padStart(2, '0')
				return `${year}-${month}-${day}`
			},
			
			// 日期选择器变更
			onDateChange(e) {
				this.formData.expected_time = e.detail.value
			},
			
			// 选择图片
			chooseImage() {
				if (this.formData.media_list.length >= 3) {
					uni.showToast({
						title: '最多上传3张图片',
						icon: 'none'
					})
					return
				}
				
				uni.chooseImage({
					count: 3 - this.formData.media_list.length,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						// 处理选择的图片
						const tempFilePaths = res.tempFilePaths
						
						// 上传图片到服务器
						tempFilePaths.forEach(path => {
							this.uploadImage(path)
						})
					}
				})
			},
			
			// 上传图片到服务器
			uploadImage(filePath) {
				uni.showLoading({
					title: '上传中...'
				})
				
				// 实际项目中应该调用API上传图片
				// 这里模拟上传成功，直接使用本地路径
				setTimeout(() => {
					uni.hideLoading()
					
					// 模拟上传成功后的返回数据
					const imageData = {
						url: filePath,
						name: filePath.substring(filePath.lastIndexOf('/') + 1)
					}
					
					this.formData.media_list.push(imageData)
				}, 500)
				
				// 实际上传代码示例：
				/*
				uni.uploadFile({
					url: 'your-upload-api-url',
					filePath: filePath,
					name: 'file',
					success: (uploadRes) => {
						uni.hideLoading()
						
						// 解析返回的数据
						const data = JSON.parse(uploadRes.data)
						if (data.code === 200) {
							this.formData.media_list.push({
								url: data.data.url,
								name: data.data.name
							})
						} else {
							uni.showToast({
								title: data.message || '上传失败',
								icon: 'none'
							})
						}
					},
					fail: (err) => {
						uni.hideLoading()
						uni.showToast({
							title: '上传失败，请重试',
							icon: 'none'
						})
						console.error('上传图片失败:', err)
					}
				})
				*/
			},
			
			// 预览图片
			previewImage(index) {
				const urls = this.formData.media_list.map(item => item.url)
				uni.previewImage({
					urls: urls,
					current: urls[index]
				})
			},
			
			// 删除图片
			deleteImage(index) {
				uni.showModal({
					title: '提示',
					content: '确定要删除这张图片吗？',
					success: (res) => {
						if (res.confirm) {
							this.formData.media_list.splice(index, 1)
						}
					}
				})
			},
			
			// 显示设备选择弹窗
			showDeviceSelector() {
				this.showDeviceModal = true
			},
			
			// 关闭设备选择弹窗
			closeDevicePopup() {
				this.showDeviceModal = false
			},
			
			// 获取设备列表
			getDeviceList() {
				this.loadingDevices = true
				
				// 不再需要从前端传递unit_id参数，后端会自动根据用户ID获取关联单元
				getAvailableDevices()
					.then(devices => {
						console.log('获取到的设备列表:', devices)
						this.deviceList = devices || []
						this.filteredDevices = [...this.deviceList]
						
						if (this.deviceList.length === 0) {
							uni.showToast({
								title: '未找到您单元内的设备',
								icon: 'none',
								duration: 2000
							})
						}
					})
					.catch(error => {
						console.error('获取设备列表失败:', error)
						uni.showToast({
							title: '获取设备列表失败',
							icon: 'none'
						})
						
						// 如果获取失败，使用空数组
						this.deviceList = []
						this.filteredDevices = []
					})
					.finally(() => {
						this.loadingDevices = false
					})
			},
			
			// 搜索设备
			searchDevices() {
				if (!this.deviceSearchKey) {
					this.filteredDevices = [...this.deviceList]
					return
				}
				
				const keyword = this.deviceSearchKey.toLowerCase()
				this.filteredDevices = this.deviceList.filter(device => 
					device.device_name.toLowerCase().includes(keyword) || 
					device.device_number.toLowerCase().includes(keyword) ||
					device.device_type.toLowerCase().includes(keyword) ||
					(device.location_desc && device.location_desc.toLowerCase().includes(keyword))
				)
			},
			
			// 选择设备
			selectDevice(device) {
				this.selectedDevice = device
				this.formData.device_id = device.device_id
				this.closeDevicePopup()
			},
			
			// 表单验证
			validateForm() {
				if (!this.formData.device_id) {
					uni.showToast({
						title: '请选择需要维保的设备',
						icon: 'none'
					})
					return false
				}
				
				if (!this.formData.content) {
					uni.showToast({
						title: '请填写维保内容',
						icon: 'none'
					})
					return false
				}
				
				if (!this.formData.expected_time) {
					uni.showToast({
						title: '请选择期望维修日期',
						icon: 'none'
					})
					return false
				}
				
				if (!this.formData.fault_description) {
					uni.showToast({
						title: '请填写故障描述',
						icon: 'none'
					})
					return false
				}
				
				return true
			},
			
			// 提交表单
			async submitForm() {
				if (!this.validateForm()) return
				
				this.submitting = true
				
				try {
					// 构建提交数据
					const repairServiceData = {
						device_id: this.formData.device_id,
						fault_description: this.formData.fault_description,
						repair_status: this.formData.repair_status,
						expected_time: this.formData.expected_time,
						media_urls: JSON.stringify(this.mediaUrls)
					}
					
					const maintenanceRecordData = {
						device_id: this.formData.device_id,
						maintenance_type: '维修', // 统一写为维修
						content: this.formData.content
					}
					
					console.log('提交的报修数据:', repairServiceData)
					console.log('提交的设备维保数据:', maintenanceRecordData)
					
					// 调用API提交数据
					const res = await createDeviceMaintenance({
						repairService: repairServiceData,
						maintenanceRecord: maintenanceRecordData
					})
					
					uni.showToast({
						title: '申请提交成功',
						icon: 'success'
					})
					
					// 触发刷新事件，通知列表页刷新
					eventBus.emit('refreshMaintenanceList')
					
					// 延迟返回上一页
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				} catch (error) {
					console.error('提交设备维保申请失败:', error)
					
					uni.showToast({
						title: error.message || '提交失败，请重试',
						icon: 'none',
						duration: 3000
					})
				} finally {
					this.submitting = false
				}
			}
		}
	}
</script>

<style lang="scss">
.apply-container {
	padding: 20rpx;
	background-color: #F8F8F8;
	min-height: 100vh;
	
	.form-card {
		background-color: #FFFFFF;
		border-radius: 12rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
		
		.form-title {
			font-size: 32rpx;
			font-weight: bold;
			margin-bottom: 30rpx;
			text-align: center;
		}
		
		.form-item {
			margin-bottom: 30rpx;
			
			.item-label {
				font-size: 28rpx;
				margin-bottom: 15rpx;
				color: #333;
				
				&.required:before {
					content: '*';
					color: #dd524d;
					margin-right: 6rpx;
				}
			}
			
			.item-content {
				.form-input, .form-textarea, .picker-view, .device-selector {
					background-color: #F8F8F8;
					border-radius: 8rpx;
					padding: 20rpx;
					font-size: 28rpx;
					width: 100%;
					box-sizing: border-box;
				}
				
				.form-textarea {
					height: 200rpx;
					width: 100%;
					box-sizing: border-box;
				}
				
				.textarea-counter {
					text-align: right;
					font-size: 24rpx;
					color: #999;
					margin-top: 10rpx;
				}
				
				.picker-view, .device-selector {
					display: flex;
					justify-content: space-between;
					align-items: center;
				}
				
				.placeholder {
					color: #BBBBBB;
				}
				
				.selected-text {
					color: #333;
				}
				
				.radio-group {
					display: flex;
					
					.radio-item {
						display: flex;
						align-items: center;
						margin-right: 60rpx;
						
						.radio-circle {
							width: 36rpx;
							height: 36rpx;
							border-radius: 50%;
							border: 2rpx solid #DDDDDD;
							display: flex;
							align-items: center;
							justify-content: center;
							margin-right: 10rpx;
							
							.radio-inner {
								width: 20rpx;
								height: 20rpx;
								border-radius: 50%;
								background-color: #2979ff;
							}
						}
						
						&.active {
							.radio-circle {
								border-color: #2979ff;
							}
						}
					}
				}

				.upload-images {
					display: flex;
					flex-wrap: wrap;
					margin-top: 10rpx;
					
					.image-item {
						width: 160rpx;
						height: 160rpx;
						margin-right: 20rpx;
						margin-bottom: 20rpx;
						position: relative;
						
						.preview-image {
							width: 100%;
							height: 100%;
							border-radius: 8rpx;
						}
						
						.delete-icon {
							position: absolute;
							top: -10rpx;
							right: -10rpx;
							width: 40rpx;
							height: 40rpx;
							background-color: rgba(0,0,0,0.5);
							border-radius: 50%;
							display: flex;
							align-items: center;
							justify-content: center;
						}
					}
					
					.upload-button {
						width: 160rpx;
						height: 160rpx;
						border: 2rpx dashed #DDDDDD;
						border-radius: 8rpx;
						display: flex;
						flex-direction: column;
						align-items: center;
						justify-content: center;
						margin-bottom: 20rpx;
						
						.upload-text {
							font-size: 24rpx;
							color: #BBBBBB;
							margin-top: 10rpx;
						}
					}
				}
				
				.upload-tip {
					font-size: 24rpx;
					color: #999;
				}
			}
		}
	}
	
	.submit-section {
		padding: 30rpx 0;
		
		.submit-btn {
			background-color: #2979ff;
			color: #fff;
			border-radius: 45rpx;
			font-size: 32rpx;
			height: 80rpx;
			line-height: 80rpx;
			
			&:disabled {
				opacity: 0.6;
			}
		}
	}
	
	/* 自定义模态框样式 */
	.custom-modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 999;
		
		.modal-mask {
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			background-color: rgba(0, 0, 0, 0.5);
		}
		
		.modal-content {
			position: absolute;
			bottom: 0;
			left: 0;
			right: 0;
			background-color: #FFFFFF;
			border-top-left-radius: 20rpx;
			border-top-right-radius: 20rpx;
			transform: translateY(0);
			transition: transform 0.3s;
			max-height: 70vh;
			
			.popup-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 30rpx;
				border-bottom: 1rpx solid #EEEEEE;
				
				.popup-title {
					font-size: 32rpx;
					font-weight: bold;
				}
				
				.popup-close {
					padding: 10rpx;
				}
			}
			
			.popup-body {
				padding: 30rpx;
				max-height: 60vh;
				
				.search-box {
					display: flex;
					align-items: center;
					background-color: #F8F8F8;
					border-radius: 8rpx;
					padding: 15rpx 20rpx;
					margin-bottom: 20rpx;
					
					.search-input {
						flex: 1;
						margin-left: 15rpx;
						font-size: 28rpx;
					}
				}
				
				.device-list {
					max-height: 50vh;
					
					.loading-devices, .empty-devices {
						padding: 30rpx 0;
						text-align: center;
						color: #999;
						font-size: 28rpx;
					}
					
					.device-item {
						display: flex;
						justify-content: space-between;
						padding: 20rpx 0;
						border-bottom: 1rpx solid #EEEEEE;
						
						&:last-child {
							border-bottom: none;
						}
						
						.device-info {
							.device-name {
								font-size: 28rpx;
								margin-bottom: 6rpx;
							}
							
							.device-number {
								font-size: 24rpx;
								color: #999;
							}
						}
						
						.device-type {
							font-size: 24rpx;
							color: #2979ff;
							background-color: rgba(41, 121, 255, 0.1);
							padding: 4rpx 16rpx;
							border-radius: 20rpx;
							height: 36rpx;
							line-height: 36rpx;
						}
					}
				}
			}
		}
	}
}
</style>